<?php
/**
 * minf - core library
 * modules/file.php
 *
 * @author per function || minf.org team
 * @version 0.beta4
 * @copyright no,no,left, minf.org, 25 February, 2009
 * @license GPL
 * @package default
 **/

function get_caller_application_class() {
	$level = 2;
	$found = false;
	for ($i=0;$i<10;$i++) {
		$class = @get_caller_class($level+$i);
		if ($class&&is_callable(array($class, '_Type'))&&call_user_func_array(array($class, '_Type'), array())=='Application') {
			$level = $level+$i;
			$found = true;
			break;
		}
	}
	if (!$found) return false;	// Cannot find calling application class
	return $class;
}

// 
function get_file($filename) {
	// probably an application calling it :)
	$class = get_caller_application_class();
	$file = findfile($filename, $class);
	if ($file) return @file_get_contents($file);
	else return false;
}
// 
function get_filedate($filename) {
	// probably an application calling it :)
	$class = get_caller_application_class();
	$file = findfile($filename, $class);
	if ($file) return @filemtime($file);
	else return false;
}

function findfile($filename, $class) {
	$path = App::GetPath($class);
	if (file_exists(USER_PATH."data/app/".strtolower($class)."/".$filename)) return USER_PATH."data/app/".strtolower($class)."/".$filename;
	elseif (file_exists($path.$filename)) return $path.$filename;
	else {
		echosys("{$class}: Cannot Find File : {$filename}", MSG_WARNING);
		return false;
	}
}

// Some space for applications to put files
function put_file($filename, $contents, $append=false) {
	$class = get_caller_application_class();
	$path = USER_PATH."data/app/".strtolower($class);
	if (!is_dir($path)) if (!@mkdir($path, 0777, true)) return false;
	return @file_put_contents(USER_PATH."data/app/".strtolower($class)."/".$filename, $contents, ($append) ? FILE_APPEND : 0);
}

function del_file($filename) {
	// probably an application calling it :)
	$class = get_caller_application_class();
	$path = App::GetPath($class);
	if (file_exists(USER_PATH."data/app/".strtolower($class)."/".$filename)) return @unlink(USER_PATH."data/app/".strtolower($class)."/".$filename);
	elseif (file_exists($path.$filename)) return @unlink($path.$filename);
	else return false;
}

// Let them check their files
function check_file($filename) {
	$class = get_caller_application_class();
	$path = App::GetPath($class);
	if (file_exists($path.$filename)) return true;
	elseif (file_exists(USER_PATH."data/app/".strtolower($class)."/".$filename)) return true;
	else return false;
}

?>